package be.dch.gui.panels;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeListener;

import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;

import org.apache.log4j.Logger;

import be.dch.gui.SwingUtils;
import be.dch.gui.layout.GarminIconRenderer;
import be.dch.typeditor.domain.GarminIcon;

public class TypEditorListPanel extends JPanel {

    private static final Logger LOG = Logger.getLogger(TypEditorListPanel.class);

    public static final String ITEM_SELECTED = "item.selected";
    private static final long serialVersionUID = 4140656145861088482L;
    private final transient JList list;
    private final transient DefaultListModel model;

    public TypEditorListPanel(final int width, final int height) {
	super();

	this.model = new DefaultListModel();
	this.list = new JList(this.model);

	this.list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
	this.list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
	this.list.setVisibleRowCount(-1);
	this.list.setCellRenderer(new GarminIconRenderer());
	this.list.addMouseListener(new MouseAdapter() {
	    @Override
	    public void mouseClicked(final MouseEvent event) {
		if (event.getClickCount() == 2) {
		    TypEditorListPanel.LOG.debug(TypEditorListPanel.this.list.getSelectedIndex());
		    final GarminIcon selected = (GarminIcon) TypEditorListPanel.this.list.getSelectedValue();
		    if (selected != null) {
			TypEditorListPanel.this.firePropertyChange(TypEditorListPanel.ITEM_SELECTED, null, selected);
		    }
		}
	    }
	});
	final JScrollPane thumbnailPanel = new JScrollPane(this.list);
	SwingUtils.setFixedDimensions(thumbnailPanel, width, height);
	this.add(thumbnailPanel);
    }

    public void setAllElements(final GarminIcon[] icons) {
	this.model.removeAllElements();
	for (final GarminIcon icon : icons) {
	    this.model.addElement(icon);
	}
    }

    public void resetAllElements() {
	this.model.removeAllElements();
    }

    public void addPropertyChangeListeren(final PropertyChangeListener listener) {
	this.addPropertyChangeListener(listener);
    }

}
